#include "netserver.h"
#include<QDebug>

#include"QJsonDocument"
#include"QJsonObject"
#include"QJsonArray"
#include"QJsonValue"

NetServer::NetServer(QObject *parent) : QObject(parent)
{
    connect(&server,&QTcpServer::newConnection,
            this,&NetServer::slot_newConnection);
}

void NetServer::startListen()
{
    server.listen(QHostAddress::Any,10086);
    //端口号随意 0-65535 但1000以内基本被占用了
}

void NetServer::sendStopToCar(const int &carId)
{
    QJsonObject obj;
    obj.insert("code",10003);//发送小车停止信息
    obj.insert("id",carId);
    for(auto item:list_socket){
        item->write(QJsonDocument(obj).toJson());//所有小车都会收到这条消息
    }
}

void NetServer::sendStartToCar(const int &carId)
{
    QJsonObject obj;
    obj.insert("code",10005);//发送小车停止信息
    obj.insert("id",carId);
    for(auto item:list_socket){
        item->write(QJsonDocument(obj).toJson());//所有小车都会收到这条消息
}
}

void NetServer::slot_newConnection()
{
    qDebug()<<"有新的连接";
    QTcpSocket *socket = server.nextPendingConnection();//会返回连接对象的socket
    list_socket.append(socket);

    connect(socket,&QTcpSocket::readyRead,
            this,&NetServer::slot_readyRead);
}

void NetServer::slot_readyRead()
{


        QTcpSocket *socket = dynamic_cast<QTcpSocket *>(sender());
        QByteArray data = socket->readAll();
        QList<QJsonObject> list_obj = splitJsonObject(data);
        for(auto obj : list_obj){
            if(obj.contains("code")) {
                // 所有的信息都会包含该字段
                int code = obj.value("code").toInt();
                switch (code) {
                case 20001:
                    // 身份信息
                {
                    QString type = obj.value("type").toString();
                    int id = obj.value("id").toInt();
        //            qDebug() << "新的连接为" << type << "，id=" << id;
                    if(type=="car"){
                        emit signal_addCar(id);
                    }
                }
                    break;
                case 30001:
                {
                    // 小车状态信息
                    int id = obj.value("id").toInt();
                    int road_id = obj.value("road_id").toInt();
                    float duration = obj.value("duration").toDouble();
                    emit signal_updateCar(id,road_id,duration);
          /*          qDebug() << "拿到了新的小车" << id << "的信息，所处道路：" <<
                                road_id << "，duration:" << duration;
                                */
                }
                    break;
                case 30002:
                {
                    //有小车请求路口信息
                    int road_id=obj.value("road_id").toInt();
                    bool ok;
                    emit signal_getCrossState(road_id,ok);
                    //信号和槽的传递有同步和异步两种方式，默认是同步的
                    //但是一旦涉及到多线程，默认的就是异步
                    //不建议将来正式项目中这么写
                    QJsonObject obj;
                    obj.insert("code",10004);
                    obj.insert("state",ok);
                    socket->write(QJsonDocument(obj).toJson());
                }
                    break;
                }
            }
        }



}

QList<QJsonObject> NetServer::splitJsonObject(const QByteArray &data)
{
    QList<QJsonObject> list_obj;
        int braceCount = 0;
        int startIndex = 0;
        for (int i = 0; i < data.size(); ++i) {
            if (data[i] == '{') {
                if (braceCount == 0) {
                    startIndex = i;
                }
                braceCount++;
            } else if (data[i] == '}') {
                braceCount--;
                if (braceCount == 0) {
                    QByteArray json = data.mid(startIndex, i - startIndex + 1);
                    QJsonDocument doc = QJsonDocument::fromJson(json);
                    QJsonObject obj = doc.object();
                    list_obj.append(obj);
                }
            }
        }
        return list_obj;
}
